package com.azxcrm.project.system.order.service;

import java.util.List;
import java.util.UUID;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.azxcrm.common.utils.DateUtils;
import com.azxcrm.common.utils.RandomUtils;
import com.azxcrm.common.utils.StringUtils;
import com.azxcrm.common.utils.security.ShiroUtils;
import com.azxcrm.framework.redis.template.service.RedisServiceImpl;
import com.azxcrm.project.monitor.workflow.common.CommonService;
import com.azxcrm.project.monitor.workflow.domain.WorkFlowApply;
import com.azxcrm.project.monitor.workflow.service.WorkFlowApplyService;
import com.azxcrm.project.system.basic.dao.IOrderModifyRecordDao;
import com.azxcrm.project.system.basic.domain.OrderModifyRecord;
import com.azxcrm.project.system.customer.domain.CustomerInfo;
import com.azxcrm.project.system.customer.service.ICustomerInfoService;
import com.azxcrm.project.system.order.dao.IOrderDao;
import com.azxcrm.project.system.order.dao.IOrderDealDao;
import com.azxcrm.project.system.order.domain.Order;
import com.azxcrm.project.system.order.domain.OrderAudit;
import com.azxcrm.project.system.order.domain.OrderDeal;
import com.azxcrm.project.system.order.domain.OrdersSet;
/**
 * 订单 服务层实现
 * 
 * @author Dustyone
 * @date 2018-09-11
 */
@Service
public class OrderServiceImpl implements IOrderService 
{
	@Autowired
	private IOrderDao orderDao;
	
	@Autowired
	private IOrderDealDao orderDealDao;
	
	@Autowired
	private IOrderModifyRecordDao  orderModifyRecordDao;
	
	/**
	 * 客户信息
	 */
	@Autowired
	private ICustomerInfoService customerInfoService;
	
	@Autowired
	private CommonService commonService;
	
	@Autowired
	private RedisServiceImpl redisService;
	
	@Autowired
	private WorkFlowApplyService workFlowApplyService;
	
	
	/**
     * 查询订单信息
     * 
     * @param orderId 订单ID
     * @return 订单信息
     */
	 @Override
	public Order selectOrderById(Integer orderId)
	{
	    return orderDao.selectOrderById(orderId);
	}
	 
	 /**
     * 查询订单信息
     * 
     * @param order 订单信息
     * @return 订单信息
     */
	@Override
	public Order selectOrderByOrder(Order order) {
		return orderDao.selectOrderByOrder(order);
	}
	
	/**
     * 查询订单列表
     * 
     * @param order 订单信息
     * @return 订单集合
     */
	 @Override
	public List<Order> selectOrderList(Order order)
	{
	    return orderDao.selectOrderList(order);
	}
	 
	 /**
     * 查询待审核订单列表
     * 
     * @param order 订单信息
     * @return 订单集合
     */
	 @Override
	public List<Order> selectOrderAuditList(Order order)
	{
	    return orderDao.selectOrderAuditList(order);
	}

	/**
	 * 查询待跟进订单列表
	 * 
	 * @param order
	 *            待跟进订单信息
	 * @return 待跟进订单集合
	 */
	@Override
	public List<Order> selectOrderFollowList(Order order) {
		return orderDao.selectOrderFollowList(order);
	}

	/**
	 * 根据部门id查询部门待分配订单条数
	 * @param deptId
	 * @return
	 */
	@Override
	public int selectOrderCount(Integer deptId) {
		return orderDao.selectOrderCount(deptId);
	}
	
    /**
     * 新增订单
     * 
     * @param order 订单信息
     * @return 结果
     */
	 @Override
	public int insertOrder(Order order)
	{
	    return orderDao.insertOrder(order);
	}
	
	/**
     * 修改订单
     * 
     * @param order 订单信息
     * @return 结果
     */
	 @Override
	public int updateOrder(Order order)
	{
	    return orderDao.updateOrder(order);
	}
	 
	/**
	 * 根据订单ID修改订单状态
	 */
	 @Override
	public int updateOrderStatusById(Order order) {
		return orderDao.updateOrderStatusById(order);
	}
	
	/**
     * 保存订单
     * 
     * @param order 订单信息
     * @return 结果
     */
	 @Override
	public int saveOrder(Order order)
	{
	    Integer orderId = order.getOrderId();
		int rows = 0;
		if (StringUtils.isNotNull(orderId))
        {
		    rows = orderDao.updateOrder(order);
		}
		else
        {
		    rows = orderDao.insertOrder(order);
		}
		return rows;
	}
	
	/**
     * 删除订单信息
     * 
     * @param orderId 订单ID
	 * @return 结果
	 */
	@Override
	public int deleteOrderById(Integer orderId)
	{
		return orderDao.deleteOrderById(orderId);
	}

	/**
     * 批量删除订单对象
     * 
     * @param orderIds 需要删除的数据ID
     * @return 结果
     */
	 @Override
	public int batchDeleteOrder(Integer[] orderIds)
	{
		return orderDao.batchDeleteOrder(orderIds);
	}

	/**
	 * 审批订单
	 * @param orderAudit
	 * @return
	 */
	@Override
	@Transactional
	public int auditOrder(OrderAudit orderAudit){
		int ret = -1;
		String cacheData = "";
		try {
			String audit = orderAudit.getAudit();
			
			if("pass".equals(orderAudit.getAudit())){
				//获取Redis缓存中的图片路径
				try {
					cacheData = (String) redisService.get(orderAudit.getShortToken());
					if("".equals(cacheData) ||cacheData == null ){
						//缓存数据已过期
						ret = -2;
						return ret;
					}
				} catch (Exception e) {
					//获取缓存数据异常
					ret = -3;
					return ret;
				}
			}
			
			//成单审核通过
			Order orderInfo = orderDao.selectOrderById(orderAudit.getOrderId());
			if(orderInfo == null){
				//订单信息异常
				ret = -4;
				return ret;
			}
			
			//审核类型:成单审核
			if(orderAudit.getAuditType() !=null && orderAudit.getAuditType() == 1){
				//成单审核类型
				if("pass".equals(audit)){
					
					//查询线索中的客户信息是否存在
					CustomerInfo customerInfo = customerInfoService.selectCustomerByIdNo(orderInfo.getCustomerClue().getCustomerIdentityNum());
					if(customerInfo == null){
						//该客户不存在时，创建新客户信息
						CustomerInfo customerInfoDe = customerInfoService.CustomerConvert(orderInfo.getCustomerClue());
						//新增客户
						customerInfoService.insertCustomerInfo(customerInfoDe);
					}
					
					//回写订单表状态
					Order order = new Order(orderInfo.getOrderId(), 5, orderAudit.getAuditType(), 2, ShiroUtils.getUserId().intValue(), ShiroUtils.getLoginName());
					orderDao.updateOrder(order);
					
					//新增订单修改记录
					OrderModifyRecord orderModifyRecord = new OrderModifyRecord(orderInfo.getOrderId(), ShiroUtils.getUserId().intValue(), 2, "成单审核成功");
					orderModifyRecordDao.insertOrderModifyRecord(orderModifyRecord);
					
					//新增成单表信息
					OrderDeal orderDeal = new OrderDeal(2, orderInfo.getOrderId(), customerInfo.getIdentityNum(), orderAudit.getContractId(), cacheData);
					orderDealDao.insertOrderDeal(orderDeal);
					
					//任何审批类型最后认领并处理任务
					commonService.completeTaskByUser(orderAudit.getTaskId(), String.valueOf(ShiroUtils.getUserId()), audit);
					ret = 1;
					return ret;
					
				}else if("reject".equals(audit)){
					//成单审核被拒
					//回写订单表订单状态:审核被拒/审核不通过
					Order order = new Order(orderInfo.getOrderId(), 4, orderAudit.getAuditType(), 3, ShiroUtils.getUserId().intValue(), ShiroUtils.getLoginName());
					orderDao.updateOrder(order);
				
					//新增订单修改记录表状态
					OrderModifyRecord orderModifyRecord = new OrderModifyRecord(orderInfo.getOrderId(), ShiroUtils.getUserId().intValue(), 3, "成单审核被拒");
					orderModifyRecordDao.insertOrderModifyRecord(orderModifyRecord);
					
					//任何审批类型最后认领并处理任务
					commonService.completeTaskByUser(orderAudit.getTaskId(), String.valueOf(ShiroUtils.getUserId()), audit);
					ret = 1;
					return ret;
				}
				
			}else if(orderAudit.getAuditType() !=null && orderAudit.getAuditType() == 2){
				//退单审核
				if("pass".equals(audit)){
					//退单审核通过
					//回写订单表状态，退单审核通过
					Order order = new Order(orderInfo.getOrderId(), 6, orderAudit.getAuditType(), 2, ShiroUtils.getUserId().intValue(), ShiroUtils.getLoginName());
					orderDao.updateOrder(order);
					
					//新增订单修改记录
					OrderModifyRecord orderModifyRecord = new OrderModifyRecord(orderInfo.getOrderId(), ShiroUtils.getUserId().intValue(), 2, "退单审核成功");
					orderModifyRecordDao.insertOrderModifyRecord(orderModifyRecord);
					
					//回写成单信息表
					OrderDeal orderDeal = new OrderDeal(3, orderInfo.getOrderId(), orderInfo.getRefundReason(), cacheData);
					orderDealDao.updateOrderDeal(orderDeal);
					
					//任何审批类型最后认领并处理任务
					commonService.completeTaskByUser(orderAudit.getTaskId(), String.valueOf(ShiroUtils.getUserId()), audit);
					ret = 1;
					return ret;
				}else if("reject".equals(audit)){
					//退单审核不通过
					//回写订单表状态:审核不通过
					Order order = new Order(orderInfo.getOrderId(), 5, orderAudit.getAuditType(), 3, ShiroUtils.getUserId().intValue(), ShiroUtils.getLoginName());
					orderDao.updateOrder(order);
					
					//新增订单修改记录
					OrderModifyRecord orderModifyRecord = new OrderModifyRecord(orderInfo.getOrderId(), ShiroUtils.getUserId().intValue(), 2, "退单审核");
					orderModifyRecordDao.insertOrderModifyRecord(orderModifyRecord);
					
					//任何审批类型最后认领并处理任务
					commonService.completeTaskByUser(orderAudit.getTaskId(), String.valueOf(ShiroUtils.getUserId()), audit);
					ret = 1;
					return ret;
				}
			}
		} catch (Exception e) {
			//任何未知异常
			ret = -5;
			return ret;
		}
		
		return ret;
	}

	@Override
	public Order selectOrder() {
		// TODO Auto-generated method stub
		return orderDao.selectOrder();
	}
	
	/**
	 * 财务创建订单
	 */
	@Override
	@Transactional
	public int foundOrder(OrdersSet ordersSet) {
		int ret = -1;
		String cacheData = "";
		try {
			String audit = ordersSet.getAudit();
			
			if("pass".equals(ordersSet.getAudit())){
				//获取Redis缓存中的图片路径
				try {
					cacheData = (String) redisService.get(ordersSet.getShortToken());
					if("".equals(cacheData) ||cacheData == null ){
						//缓存数据已过期
						ret = -2;
						return ret;
					}
				} catch (Exception e) {
					//获取缓存数据异常
					ret = -3;
					return ret;
				}
			}
			
			//成单列表创建订单需要的信息
			Order order = new Order(1, 2, 5, ShiroUtils.getUser().getUserId().intValue(), ShiroUtils.getUser().getLoginName(),
					ShiroUtils.getUser().getLoginName(), ordersSet.getTypeId(), ordersSet.getTypeName(),
					ordersSet.getProductId(), ordersSet.getFullName(), ordersSet.getSalesUserId(), 
					ordersSet.getSalesUserName(), 0);
			//随机生成订单号
			int a = RandomUtils.randomCommon(0, 9, 5);
			String time = DateUtils.getDateStamp(); 
			order.setOrderNum("azx"+time+""+a+"");
			order.setDeptId(ordersSet.getDeptId());
			order.setDeptName(ordersSet.getDeptName());
			order.setClueId(0);
			orderDao.insertOrder(order);
			Order selOrder=new Order();
			selOrder.setOrderId(order.getOrderId());
			//成单审核类型
			if("pass".equals(audit)){					
				//新增成单表信息
				OrderDeal orderDeal = new OrderDeal(1, selOrder.getOrderId(), ordersSet.getCustomerIdentity(), ordersSet.getContractId(), cacheData);
				orderDealDao.insertOrderDeal(orderDeal);
				
				//新增订单修改记录
				OrderModifyRecord orderModifyRecord = new OrderModifyRecord(selOrder.getOrderId(), ShiroUtils.getUserId().intValue(), 2, "新增订单成功");
				orderModifyRecordDao.insertOrderModifyRecord(orderModifyRecord);
				ret = 1;
				return ret;					
			}		
		} catch (Exception e) {
			//任何未知异常
			ret = -4;
			return ret;
		}
		return ret;
	}
	
	/**
	 * 发起退单
	 */
	@Override
	@Transactional
	public int flowOrderDeal(OrdersSet ordersSet) {
		int ret = -1;
		String cacheData = "";
		try {
			String audit = ordersSet.getAudit();
			if("pass".equals(ordersSet.getAudit())){
				//获取Redis缓存中的图片路径
				try {
					cacheData = (String) redisService.get(ordersSet.getShortToken());
					if("".equals(cacheData) ||cacheData == null ){
						//缓存数据已过期
						ret = -2;
						return ret;
					}
				} catch (Exception e) {
					//获取缓存数据异常
					ret = -3;
					return ret;
				}
			}
			
			//退单审核类型
			if("pass".equals(audit)){
				//退单审核通过
				//回写订单表状态
				Order order = new Order(ordersSet.getOrderId(), 2, 6);
				orderDao.updateOrder(order);
				
				//回写成单表状态
				OrderDeal orderDeal = new OrderDeal(3, ordersSet.getOrderId(), ordersSet.getRefundsReason(), cacheData);
				orderDealDao.updateOrderDeal(orderDeal);
				
				//新增订单修改记录
				OrderModifyRecord orderModifyRecord = new OrderModifyRecord(ordersSet.getOrderId(), ShiroUtils.getUserId().intValue(), 2, "发起退单成功");
				orderModifyRecordDao.insertOrderModifyRecord(orderModifyRecord);
				
				ret = 1;
				return ret;
				
			}
		} catch (Exception e) {
			//任何未知异常
			ret = -4;
			return ret;
		}		
		return ret;
	}
	
	/**
	 * 查看指定产品是否已被订单引用
	 * @return true有有引用 false无引用
	 */
	@Override
	public boolean checkProductCasecaded(Integer productId) {
		int result = orderDao.checkProductCasecaded(productId);
		return result > 0 ? true : false;
	}
	
	/**
	 * 统计当前月份业务员的订单数
	 * @param Order
	 * @return
	 */
	@Override
	 public Order countOrderById(Order Order){
		 return orderDao.countOrderById(Order);
	 }
	 
	 /**
	 * wap统计当前业务员的总订单数和价格
	 * @param Order
	 * @return
	 */
	@Override
	 public Order countOrder(Order Order){
		 return orderDao.countOrder(Order);
	 }
	 
	 /**
	 * 查看指定线索是否被订单引用
	 * @param clueId
	 * @return 结果true:已被引用；false未被引用
	 */
	@Override
	public boolean checkCustomerClueCasecaded(Integer clueId) {
		int result = orderDao.checkCustomerClueCasecaded(clueId);
		return result > 0 ? true : false;
	}

	//wap业务员发起退单
	@Override
	@Transactional
	public int wapFlowOrderDeal(Order order) {

		int ret = -1;
		try {
			//开启发起退单流程
			//发起退单时开启退单审批工作流
			String businessId = UUID.randomUUID().toString();
			//flowId 1:成单审批 2：退单审批
			WorkFlowApply workFlowApply = new WorkFlowApply(ShiroUtils.getUserId().intValue(), businessId, 2, "退单审批", order.getOrderId());
			if (workFlowApplyService.saveWorkFlowApply(workFlowApply) > 0) {
				//开启退单审批流程
			commonService.startProcess(businessId,workFlowApply);
			
			//退单审核通过，在工作流开启成功之后处理
			//回写订单表状态
			Order refundOrder = new Order(order.getOrderId(), 3, 2, 1, order.getRefundReason());
			refundOrder.setOrderType(1);
			orderDao.updateOrder(refundOrder);
			
			//新增订单修改记录
			OrderModifyRecord orderModifyRecord = new OrderModifyRecord(order.getOrderId(), ShiroUtils.getUserId().intValue(), 2, "退单审核");
			orderModifyRecordDao.insertOrderModifyRecord(orderModifyRecord);
			ret = 1;
			}
			return ret;
		} catch (Exception e) {
			e.printStackTrace();
		}		
		return ret;
	}
	
	/**
	 * 根据业务员手机号查询用户的派单记录
	 * @param order
	 * @return
	 */
	@Override
	public List<Order> selectOrderByPhone(Order order) {
		// TODO Auto-generated method stub
		return orderDao.selectOrderByPhone(order);
	}

	/**
	  * 根据产品类型统计不同状态下的订单数量
	  * @param typeId
	  * @return 
	  */
	@Override
	public List<Order> selectStatusCount(Integer typeId) {
		return orderDao.selectStatusCount(typeId);
	}

	/**
	  * 根据产品类型统计不同状态下的订单数量总合
	  * @return 
	  */
	@Override
	public List<Order> selectSumStatusCount() {
		return  orderDao.selectSumStatusCount();
	}
	
	/**
	 * 根据订单id查询待处理订单详情
	 * @param orderId
	 * @return
	 */
	@Override
	public Order selectOrderByOrderId(Integer orderId) {
		// TODO Auto-generated method stub
		return orderDao.selectOrderByOrderId(orderId);
	}
}
